"use strict";

// @ts-check
const path = require("node:path");
const parse5 = require("parse5");

const treeAdapter = parse5.defaultTreeAdapter;

/**
 * @param {string} html
 * @returns {string}
 */
function processorParser5(html) {
  const document = parse5.parse(html, { sourceCodeLocationInfo: true });
  /**
   * @param {{childNodes: parse5.DefaultTreeAdapterTypes.ChildNode[]}} node
   * @param {(node: parse5.DefaultTreeAdapterTypes.Element) => void=} doWork
   * @returns {void}
   */
  function walk(node, doWork) {
    for (const n of node.childNodes) {
      if (treeAdapter.isElementNode(n)) {
        doWork?.(n);
        walk(n);
      }
    }
  }
  /**
   * @param {parse5.DefaultTreeAdapterTypes.Element} node
   */
  function generateAttrs(node) {
    node.attrs.push({
      name: "data-inspect",
      value: `${path.relative(process.cwd(), __filename)}:${node.sourceCodeLocation?.startLine || ""}:${node.sourceCodeLocation?.startCol || ""}:${node.sourceCodeLocation?.endLine || ""}:${node.sourceCodeLocation?.endCol || ""}:${node.tagName}`,
    });
  }
  walk(document, generateAttrs);
  return parse5.serialize(document);
}

module.exports = { processorParser5 };
